package com.lbh.structures.components.physics;

import com.alibaba.fastjson.annotation.JSONField;
import com.lbh.structures.components.Component;
import com.lbh.structures.math.Quaternion;
import com.lbh.structures.math.Vector3;
import com.lbh.time.Time;

/***
 * project:JRuntime
 * package:com.lbh.structures.components.physics
 *
 * @author user:lenovo QQ:1601078366
 * @date 2021/10/21 3:09
 * @version V1.0
 */
public class Rigidbody extends Component {

    private static final Vector3 GRAVITY = new Vector3(0.0F, -9.8F, 0.0F);

    @JSONField(name = "type")
    public Class<Rigidbody> type = Rigidbody.class;
    @JSONField(name = "mass")
    public float mass;
    @JSONField(name = "velocity")
    public Vector3 velocity;
    @JSONField(name = "torque")
    public Vector3 torque;
    @JSONField(name = "useGravity")
    public boolean useGravity;

    public Rigidbody(){
        mass = 1.0F;
        velocity = Vector3.zero.clone();
        torque = Vector3.zero.clone();
        useGravity = true;
    }

    @Override
    public void start() {

    }

    @Override
    public void update() {
        gameObject.transform.position.add(velocity.clone().mul(Time.deltaTime));
        if (useGravity){
            Vector3 delta = GRAVITY.clone().mul(Time.deltaTime);
            velocity.add(delta);
            gameObject.transform.position.add(delta.mul(Time.deltaTime * 0.5F));
        }
        if (torque.magnitudeSqr() > 0.0F) {
            Quaternion.axisAngle(torque.normal(), 57.29577951308F * torque.magnitude());
        }
    }
}
